package com.menhai.personmanagement.controller;

import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.SpecCaptcha;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 验证码Controller
 * @author: 高云雷
 * @createTime: 2023/8/18 16:50
 * @param:
 * @return:
 **/
@Slf4j
@RestController
@RequestMapping("/checkCode")
public class CheckCodeController {

    @RequestMapping(value = "/getCheckCode")
    public void CodeCheck(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 设置请求头输入为图片类型
        response.setContentType("image/jpg");
        // 设置不用缓存，防止验证码不刷新
        response.setHeader("Pargam","No-cache");
        response.setHeader("Cache-Control","no-cache");
        // 设置过期时间，永不失效
        response.setDateHeader("Expires",0);

        // 算术类型（长，宽，几个数的运算）
//        ArithmeticCaptcha captcha = new ArithmeticCaptcha(130, 48);
//        captcha.setLen(3);  // 几位数运算，默认是两位
//        System.out.println(captcha.getArithmeticString()); // 获取运算公式 5x0+5=?
//        System.out.println(captcha.text()); // 获取验证码结果

        // 图片英语字母数字类型
        SpecCaptcha captcha = new SpecCaptcha(130, 48);

        // 英语字母数字gif类型的
        //GifCaptcha captcha = new GifCaptcha(130, 48,4);

        // 中文类型的
        //ChineseCaptcha captcha = new ChineseCaptcha(130, 48,3);

        // 中文gif类型
        //ChineseGifCaptcha captcha = new ChineseGifCaptcha(130, 48,4);
        System.out.println("======" + captcha.text());
        request.getSession().setAttribute("verifyCode",captcha.text().toLowerCase());


        // 输出验证码
        try {
            captcha.out(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @PostMapping("/verify")
    public Map<String,Object> verify(@RequestParam("code") String code, HttpSession session) {
        Map<String,Object> map = new HashMap();

        if (StringUtils.isEmpty(code)) {
            map.put("success",false);
            map.put("msg","验证码不能为空");
            return map;
        }
        String kapchaCode = session.getAttribute("verifyCode") + "";
        System.out.println(kapchaCode +"======"+ code);
        if (StringUtils.isEmpty(kapchaCode) || !code.toLowerCase().equals(kapchaCode)) {
            map.put("success",false);
            map.put("msg","验证码错误");
            return map;
        }
        map.put("success",true);
        map.put("msg","验证成功");
        return map;
    }

}
